package com.oa.tools.controller;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.oa.tools.dao.PersonDAO;
import com.oa.tools.jobs.DynamicJob;
import com.oa.tools.utils.FileUtil;
import com.oa.tools.utils.oa.DecryptionInputStream;

@RestController
@RequestMapping(path = "file")
public class OAFileController {
	

	@Autowired
	PersonDAO personDAO;
	
	public static final Logger logger = LoggerFactory.getLogger(DynamicJob.class);
	
	@RequestMapping({ "download/{fdId}" })
	public void download(HttpServletRequest request,HttpServletResponse response,@PathVariable(name="fdId") String fdId) throws Exception {
		Map<String,String> fileInfo= personDAO.selectOAFileById(fdId);
		String fileName = fileInfo.get("FILENAME");
		String fileLocalPath = fileInfo.get("FILELOCALPATH");
		logger.info("fileInfo:"+fileInfo+",fdId："+fdId);
		response.setHeader("content-type", "application/octet-stream");
	    response.setContentType("application/octet-stream");
	    // 下载文件的默认名称
	    response.setHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode(fileName, "utf-8"));
	    
	    InputStream input = FileUtil.readFile("/home/oa/OAfiles/resource"+fileLocalPath);
	    InputStream decrypInput = new DecryptionInputStream(input);
	    byte[]data = new byte[decrypInput.available()];
	    decrypInput.read(data);
	    FileUtil.closeStream(decrypInput);
	    FileUtil.closeStream(input);
	    OutputStream os = response.getOutputStream();
	    os.write(data);
	    FileUtil.closeStream(os);
	}

}
